<?php

namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\Session;
use think\Request;
use think\facade\Cache;

class Login extends BaseController
{
    /**
     * 商城----用户注册
     */
    public function register(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $code = $request->param('code');//上级ID
        $vcode = $request->param('vcode');//验证码
        $school_id = $request->param('school_id');//学校ID
        $dormitory_id = $request->param('dormitory_id');//宿舍楼ID
        $floor_id = $request->param('floor_id');//楼层ID
//        $account = $request->param('account');//账号
        $pwd = $request->param('pwd');//密码
        $phone = $request->param('phone');//手机号
        $address = $request->param('address');//地址
        $gender = $request->param('gender');//性别
        $name = $request->param('name');//真实姓名
        $openid = $request->param('openid');//openid
        if (strlen(trim($pwd)) < 6 || strlen(trim($pwd)) > 12)
            return jsonFail('密码必须是在6到12位之间');
//        if (strlen(trim($account)) < 6 || strlen(trim($account)) > 12)
//            return jsonFail('用户名必须是在6到12位之间');
        if ($pwd == '123456') return jsonFail('密码太过简单，请输入较为复杂的密码');
//        if (!preg_match("/^[A-Za-z0-9]+$/", $account)) {
//            return jsonFail('用户名不能包含中文和特殊字符！');
//        }
        if (!preg_match("/^[A-Za-z0-9]+$/", $pwd)) {
            return jsonFail('密码不能包含中文和特殊字符！');
        }
        if (empty($vcode)) return jsonFail('验证码不能为空', '', 201);
        if (empty($school_id)) return jsonFail('学校ID不能为空', '', 201);
        if (empty($dormitory_id)) return jsonFail('宿舍楼ID不能为空', '', 201);
//        if (empty($account)) return jsonFail('账号不能为空', '', 201);
        if (empty($pwd)) return jsonFail('密码不能为空', '', 201);
        if (empty($phone)) return jsonFail('手机号不能为空', '', 201);
        if (is_null($gender)) return jsonFail('性别不能为空', '', 201);
        if (empty($address)) return jsonFail('地址不能为空', '', 201);
        if (empty($name)) return jsonFail('手机号不能为空', '', 201);
        if (empty($openid)) return jsonFail('openid不能为空', '', 201);
        if (empty($floor_id)) return jsonFail('楼层ID不能为空', '', 201);
        $operate_id = Db::table('eb_school')->where('id', $school_id)->field('operate_id')->find();
        $pid_user = [];
        if ($code) {//如果填写了邀请码
            $pid_user = Db::table('eb_user')->where('code', $code)->find();
        }
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $orderSn = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        $user = Db::table('eb_user')->where('openid', $openid)->find();
        if (!empty($user['name'])) return jsonFail('一个微信号只能注册一个账户');
        try {
            $res = Cache::store('redis')->handler()->get('Z' . $phone);
            if (empty($res)) return jsonFail('验证码已过期，请重新获取');
            if ($res != $vcode) return jsonFail('验证码不正确');
            $res = Db::table('eb_user')->where('openid', $openid)->update([
                'pid' => $pid_user ? $pid_user['id'] : 0,
                'code' => $orderSn,
                'school_id' => $school_id,
                'dormitory_id' => $dormitory_id,
                'floor_id' => $floor_id,
//                'account' => $account,
                'pwd' => sha1($pwd),
                'phone' => $phone,
//                'address' => $address,
                'gender' => $gender,
                'name' => $name,
                'operate_id' => $operate_id['operate_id'],
                'create_time' => time(),
            ]);
            if ($res != 0) {
                $data = [
                    'id' => $user['id'],
                    'integral' => 0,
                    'school_id' => $school_id,
                    'dormitory_id' => $dormitory_id,
                    'is_system_order_taking' => -1,
                ];
                $addRtn = Cache::store('redis')->handler()->hMSet('dxsd-user-' . $user['id'], $data);
                if ($addRtn === false) {
                    Db::rollback();
                    return jsonFail('添加失败！');
                }
            }
            $address_data = [
                'uid' => $user['id'],
                'dormitory_id' => $dormitory_id,
                'floor_id' => $floor_id,
                'address' => $address,
                'phone' => $phone,
                'name' => $name,
                'is_default' => 1,
                'add_time' => time(),
            ];
            $address_id = Db::table('eb_user_address')->insertGetId($address_data);
            if ($address_id != 0) {
                $addRtn = Cache::store('redis')->handler()->hSet('dxsd-useraddress-' . $user['id'], $address_id, json_encode([$address_id => $address_data]));
                if ($addRtn === 1) {
                    Db::commit();
                    return jsonSuccess('添加成功');
                } else {
                    Db::rollback();
                    return jsonFail('系统错误~');
                }
            } else {
                Db::rollback();
                return jsonFail('系统错误~');
            }
        } catch (\Exception $e) {
            Db::rollback();
            return jsonFail($e->getMessage());
        }
    }

    /**
     * 商城----获取学校列表
     */
    public function school_list(Request $request)
    {
        $data = Db::table('eb_school')->field('id,name,logo')->select()->toArray();
        return jsonSuccess('获取成功！', ['data' => $data]);
    }

    /**
     * 商城----获取协议
     */
    public function get_config(Request $request)
    {
        $data = Db::table('eb_config')->where('name', 'agreement')->field('value')->find();
        return jsonSuccess('获取成功！', ['data' => $data]);
    }

    /**
     * 商城----通过学校ID获取楼栋
     */
    public function select_storied(Request $request)
    {
        $field = 'a.id,a.name,a.school_id,b.id as floor_id,b.name as floor_name';
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $school_id = $request->param('school_id');//类型
        $data = Db::table('eb_dormitory')->alias('a')
            ->leftJoin('eb_floor b', 'a.id = b.dormitory_id')
            ->where('a.school_id', $school_id)
            ->field($field)
            ->select()->toArray();
        $NewData = self::GetRepeatValGroup($data, 'id');//TODO 组合数据
        return jsonSuccess('获取成功', array_values($NewData));
    }

    /**组合数据，相同的分类为二维，商品为三维
     * @param array $input
     * @return Json
     */
    public static function GetRepeatValGroup($arr, $keys)
    {
        if (!is_array($arr) || !$keys) {
            return false;
        }
        $temp = array();
        foreach ($arr as $key => $val) {
            $temp[$val[$keys]]['id'] = $val['id'];
            $temp[$val[$keys]]['name'] = $val['name'];
            $temp[$val[$keys]]['school_id'] = $val['school_id'];
            if (!empty($val['floor_id'])) {
                $temp[$val[$keys]]['floor'][] = $val;
                foreach ($temp[$val[$keys]]['floor'] as $key => &$value) {
                    unset($value['id']);
                    unset($value['school_id']);
                    unset($value['name']);
                }
            }
//            if(empty($temp[$val[$keys]]['floor'])) unset($temp[$val[$keys]]['floor']);
        }
        return $temp;
    }

    /**
     * 商城----获取用户注册协议
     */
    public function getUserReg(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $data = Db::table('eb_config')->where('id', 4)->field('value')->find();
        return jsonSuccess('获取成功！', ['data' => $data]);
    }


    /**
     * 登录--返回token
     */
    public function verify_second(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $type = $request->param('type');
        $phone = $request->param('phone');
        $account = $request->param('account');
        $pwd = $request->param('pwd');
        $Code = $request->param('Code');//短信验证码
        $types = $request->param('types');//角色类型 1：财务员  2：装箱员  4：大配送员 3：楼栋管理员
        //检验验证码
        if (empty($type)) return jsonFail('登录类型不能为空');
        switch ($type) {
            case 1://管理员登录
                if (empty($account)) return jsonFail('用户名不能为空');
                $admin = Db::table('eb_admin')->where('account', $account)->field('id,pwd,type,account,status,name')->find();
                break;
            case 2://用户登录
                if (empty($phone)) return jsonFail('手机号码不能为空');
                $admin = Db::table('eb_user')->alias('a')
                    ->join('eb_user_address e', 'e.uid = a.id')
                    ->join('eb_floor f', 'e.floor_id = f.id')
                    ->join('eb_school b', 'a.school_id = b.id')
                    ->join('eb_dormitory c', 'e.dormitory_id = c.id')
                    ->join('eb_admin d', 'b.operate_id = d.id')
                    ->where('e.status', 1)
                    ->where('e.is_default', 1)
                    ->where('a.phone', $phone)
                    ->field('e.floor_id,a.code,a.pwd,e.dormitory_id,a.id,a.integral,a.name,a.openid,a.phone,a.portrait,a.remark,a.school_id,f.name as address_floor_name,a.type,a.username,b.is_go_up,b.name as school_name,e.id as address_id,e.name as consignee_name,e.phone as consignee_phone,e.address as consignee_address,c.name as dormitory_name,d.phone as operate_phone')
                    ->find();
                $delivery = Cache::store('redis')->handler()->hGet('dxsd-school-' . $admin['school_id'], 'delivery');
                //配送费
                $admin['delivery'] = $delivery;
                //系统配置提示
                $admin['automatic_refuse'] = Db::table('eb_config')->where('name', 'automatic_refuse')->value('value');
                break;
            case 3://学校管理人员登录
                if (empty($phone) || empty($Code) || empty($types)) return jsonFail('缺少参数');
//                $res =  Cache::store('redis')->handler()->get('A' . $phone);
//                if (empty($res)) return jsonFail('验证码已过期，请重新获取');
//                if ($res != $Code) return jsonFail('验证码不正确');
                $admin = Db::table('eb_school_role')->where('type', $types)->where('phone', $phone)->find();
        }
        if (empty($admin)) return jsonFail('用户不存在');
        if ($type == 1 && $admin['status'] == 0) return jsonFail('账号已被禁用，请联系管理员');
//        if (!ctype_alnum($account)) jsonFail('用户名只能为数字或字母组合，不能用特殊字符');
        $error = Session::get('login_error') ?: ['num' => 0, 'time' => time()];
        $error['num'] = 0;
        if ($error['num'] >= 5 && $error['time'] > strtotime('- 5 minutes'))
            return jsonFail('登录错误次数已最大，请稍后尝试');
        $res = true;
        if ($type != 3) $res = self::login($admin, $pwd);
        //检验帐号密码
        if ($res) {
            unset($admin['pwd']);
            $token = self::createToken($admin, $type);
            //$send = new \WxSendApi();
            //$ds = json_decode($send->is_subscribe($admin['openid']), true);
            return jsonSuccess('登录成功', ['token' => $token, 'expires_time' => 43200, 'roleinfo' => $admin]);
        } else {
            $error['num'] += 1;
            $error['time'] = time();
            Session::set('login_error', $error);
            return jsonFail('密码错误，请重新输入');
        }
    }

    /** 检查密码是否正确
     * @param $account 账号
     * @param $pwd 密码
     * @param $type 类型
     */
    public function login($admin, $pwd)
    {
        if (!array_key_exists('pwd', $admin)) return false;
        if (sha1($pwd) != $admin['pwd']) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 生成token
     */
    public function createToken($admin, $type)
    {
        switch ($type) {
            case 1://管理员登录
                $token = md5('token+admin' . $type . $admin['id']);
                break;
            case 2://用户登录
                $token = md5('token+user' . $type . $admin['id']);
                break;
            case 3://学校人员登录
                $token = md5('token+school' . $type . $admin['id']);
                break;
        }
        $res = Cache::store('redis')->handler()->set($token, $admin['id'], 43200);
        return $token;
    }

    /**注销登陆
     * @return mixed
     */
    public function login_out(Request $request)
    {
        if (!request()->isPost()) return app('json')->fail('请采用正确的方式登录!');
        $token = $request->param('token');//获取token
        if (empty($token)) return jsonFail('登录失效');
        $redis = Cache::store('redis')->handler();
        $res = $redis->del($token);
        if ($res === 1) {
            return jsonSuccess('退出成功!');
        } else {
            return jsonFail('退出失败!');
        }
    }

    /**发送短信
     * @return mixed
     */
    public function send_msg(Request $request)
    {
        if (!request()->isPost()) return app('json')->fail('请采用正确的方式登录!');
        $phone = $request->param('phone');//手机号码
        $type = $request->param('type');//注册加Z，忘记密码加Y，学校管理人员加A
        $code = substr(microtime(), -6);// 验证码
        $expire = 3; // 验证码有效时间
        try {
            $res = json_decode(Send_msg('tx', $phone, 'template2', ['code' => $code,'expire' => $expire]), true);
            if ($res['code'] == 200) {
                $res = Cache::store('redis')->handler()->set($type . $phone, $code, 60 * $expire);//注册加Z，忘记密码加Y
                if ($res != 0) return jsonSuccess('发送成功');
                return jsonFail('发送失败');
            } else {
                return jsonFail('发送失败');
            }
        } catch (\Exception $e) {
            return jsonFail($e->getMessage());
        }
    }

    /**修改密码
     * @param Request $request
     */
    public function change_pwd(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $type = $request->param('type');//1:用户 2：商户
        $phone = $request->param('phone');//手机号码
//        $account = $request->param('account');//用户名
        $code = $request->param('code');//验证码
        $pwd = $request->param('pwd');//一次次密码
        $ckpwd = $request->param('ckpwd');//二次密码
        if (is_null($type) || empty($phone) || empty($code) || empty($pwd) || empty($ckpwd)) return jsonFail('缺少参数');
        try {
            Db::startTrans();
            $res = Cache::store('redis')->handler()->get('Y' . $phone);
            if (empty($res)) return jsonFail('验证码已过期，请重新获取');
            if ($res != $code) return jsonFail('验证码不正确');
            if ($pwd != $ckpwd) return jsonFail('密码不一致');
            if ($type == 1) {
                $ress = Db::table('eb_user')->where('phone', $phone)->update(['pwd' => sha1($pwd)]);
            } else {
                $ress = Db::table('eb_store')->where('bank_phone', $phone)->update(['pwd' => sha1($pwd)]);
            }
            if ($ress != 0) {
                Db::commit();
                return jsonSuccess('重置成功！');
            } else {
                Db::rollback();
                return jsonFail('重置失败');
            }
        } catch (\Exception $e) {
            return jsonFail($e->getMessage());
        }
    }



}
